package com.feihong.txgw.ui.activity.base;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.SerializableHashMap;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.just.agentweb.AgentWeb;

import butterknife.BindView;


/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 * WebView 页面
 */
public class WebViewActivity extends BaseActivity {

    @BindView(R.id.activity_web_webviewframe) RelativeLayout mWebviewFrame;
    private AgentWeb.PreAgentWeb mPreAgenWeb;
    private AgentWeb mAgentWeb;
    public static final String INTENT_WEBURL = "intent_weburl";
    public static final String INTENT_TITLE = "intent_title";
    public static final String INTENT_PARAMS = "intent_params";

    private String pageTitle = "";
    private String pageUrl = "";
    private String singUrl = "";
    private SerializableHashMap mParamsMap;
    private String signStr;

    @BindView(R.id.connect_net_error_layout) LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout) LinearLayout mRequeryDataBtn;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 10) {
                singUrl = pageUrl + new SignToken().setSigen(mParamsMap.getMap());
                bindData();
            }else if(msg.what == 11){
                mConnectErrorLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        pageTitle = bundle.getString(INTENT_TITLE);
        mParamsMap = (SerializableHashMap) bundle.getSerializable(INTENT_PARAMS);
        pageUrl = bundle.getString(INTENT_WEBURL);

        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshToken();
            }
        });
        setPageTitle(pageTitle+" ");
        setBackButtonFinish();

        mPreAgenWeb = AgentWeb.with(this)
                .setAgentWebParent(mWebviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
        loadPage();
    }

    private void loadPage() {
        if (mParamsMap == null){
            singUrl = pageUrl;
            bindData();
        }else{
            refreshToken();
        }
    }


    private void refreshToken() {
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Message message = Message.obtain();
                if (RefreshToken.getInstance().RetrofitRefreshTokenForGet()) {
                    message.what = 10;
                }else {
                    message.what = 11;
                }
                mHandler.sendMessage(message);
            }
        });
    }

    //WebViewClient
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
    };

    private void back() {
        finish();
        System.gc();
        System.gc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if(webView.canGoBack())
//            {
//                webView.goBack();
//                return true;
//            }
            back();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void bindData() {
        LogUtils.i(TAG + "请求url:"+singUrl);
        mAgentWeb = mPreAgenWeb.go(singUrl);

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        if(mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        back();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mAgentWeb != null) {
            mAgentWeb.destroy();
        }
    }
}
